import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { questionApi } from '@/api/question'
import { favoriteApi } from '@/api/favorite'
import type { 
  Question, 
  Tag, 
  QuestionFilters, 
  PaginationResult,
  Submission,
  ProgrammingLanguage
} from '@/types'

export const useQuestionStore = defineStore('question', () => {
  // 状态
  const questions = ref<Question[]>([])
  const currentQuestion = ref<Question | null>(null)
  const tags = ref<Tag[]>([])
  const favorites = ref<Question[]>([])
  const submissions = ref<Submission[]>([])
  const loading = ref(false)
  const pagination = ref({
    page: 1,
    page_size: 20,
    total: 0,
    total_pages: 0,
    has_next: false,
    has_prev: false
  })

  // 筛选条件
  const filters = ref<QuestionFilters>({
    page: 1,
    page_size: 20,
    tags: [],
    difficulty: [],
    status: [],
    search: ''
  })

  // 计算属性
  const hasQuestions = computed(() => questions.value.length > 0)
  const hasTags = computed(() => tags.value.length > 0)
  const isFiltered = computed(() => 
    filters.value.tags && filters.value.tags.length > 0 ||
    filters.value.difficulty && filters.value.difficulty.length > 0 ||
    filters.value.status && filters.value.status.length > 0 ||
    filters.value.search !== ''
  )

  // 获取题目列表
  const fetchQuestions = async (newFilters?: Partial<QuestionFilters>) => {
    try {
      loading.value = true
      
      // 合并筛选条件
      if (newFilters) {
        filters.value = { ...filters.value, ...newFilters }
      }

      const response = await questionApi.getQuestions(filters.value)
      
      if (response.data) {
        questions.value = response.data.data
        pagination.value = {
          page: response.data.page,
          page_size: response.data.page_size,
          total: response.data.total,
          total_pages: response.data.total_pages,
          has_next: response.data.has_next,
          has_prev: response.data.has_prev
        }
        // 刷新后同步收藏标记：若本地未加载收藏，则拉取一次并给题目打上 is_favorited
        if (!favorites.value || favorites.value.length === 0) {
          await fetchFavoriteQuestions(1, 1000)
        }
        const favIds = new Set((favorites.value || []).map(q => q.id))
        questions.value = (questions.value || []).map(q => ({
          ...q,
          is_favorited: favIds.has(q.id)
        }))
      }
      
      return true
    } catch (error) {
      console.error('Fetch questions error:', error)
      return false
    } finally {
      loading.value = false
    }
  }

  // 获取题目详情
  const fetchQuestion = async (questionId: number) => {
    try {
      loading.value = true
      const response = await questionApi.getQuestion(questionId)
      
      if (response.data) {
        currentQuestion.value = response.data
        // 同步单题收藏标记
        if (!favorites.value || favorites.value.length === 0) {
          await fetchFavoriteQuestions(1, 1000)
        }
        const favIds = new Set((favorites.value || []).map(q => q.id))
        if (currentQuestion.value) {
          ;(currentQuestion.value as any).is_favorited = favIds.has(currentQuestion.value.id)
        }
        return response.data
      }
      
      return null
    } catch (error) {
      console.error('Fetch question error:', error)
      return null
    } finally {
      loading.value = false
    }
  }

  // 获取标签列表
  const fetchTags = async () => {
    try {
      const response = await questionApi.getTags()
      if (response.data) {
        tags.value = response.data
      }
    } catch (error) {
      console.error('Fetch tags error:', error)
    }
  }

  // 设置筛选条件
  const setFilters = (newFilters: Partial<QuestionFilters>) => {
    filters.value = { ...filters.value, ...newFilters }
  }

  // 清空筛选条件
  const clearFilters = () => {
    filters.value = {
      page: 1,
      page_size: 20,
      tags: [],
      difficulty: [],
      status: [],
      search: ''
    }
  }

  // 搜索题目
  const searchQuestions = async (keyword: string) => {
    try {
      loading.value = true
      filters.value.search = keyword
      filters.value.page = 1 // 搜索时重置页码
      
      return await fetchQuestions()
    } catch (error) {
      console.error('Search questions error:', error)
      return false
    }
  }

  // 获取收藏的题目
  const fetchFavoriteQuestions = async (page = 1, pageSize = 20) => {
    try {
      loading.value = true
      const response = await favoriteApi.getFavoriteQuestions({
        page,
        page_size: pageSize
      })
      
      if (response.data) {
        favorites.value = response.data.items
        // 若需要分页可在此对 pagination.value 做兼容赋值
        return response.data
      }
      
      return null
    } catch (error) {
      console.error('Fetch favorite questions error:', error)
      return null
    } finally {
      loading.value = false
    }
  }

  // 收藏题目
  const favoriteQuestion = async (questionId: number) => {
    try {
      const resp = await favoriteApi.toggleFavorite(questionId)
      const targetState = !!resp.data?.is_favorited
      
      // 更新本地状态
      const question = questions.value.find(q => q.id === questionId) || currentQuestion.value
      if (question) {
        ;(question as any).is_favorited = targetState
      }

      // 同步 favorites 列表
      if (targetState) {
        const exists = favorites.value.some(q => q.id === questionId)
        if (!exists && question) {
          favorites.value = [...favorites.value, { ...question } as Question]
        }
      } else {
        favorites.value = favorites.value.filter(q => q.id !== questionId)
      }
      
      return true
    } catch (error) {
      console.error('Favorite question error:', error)
      return false
    }
  }

  // 取消收藏题目
  const unfavoriteQuestion = async (questionId: number) => {
    try {
      const resp = await favoriteApi.toggleFavorite(questionId)
      const targetState = !!resp.data?.is_favorited
      
      // 更新本地状态
      const question = questions.value.find(q => q.id === questionId) || currentQuestion.value
      if (question) {
        ;(question as any).is_favorited = targetState
      }
      
      // 同步 favorites 列表
      if (!targetState) {
        favorites.value = favorites.value.filter(q => q.id !== questionId)
      } else if (question) {
        const exists = favorites.value.some(q => q.id === questionId)
        if (!exists) {
          favorites.value = [...favorites.value, { ...question } as Question]
        }
      }
      
      return true
    } catch (error) {
      console.error('Unfavorite question error:', error)
      return false
    }
  }

  // 提交代码
  const submitCode = async (data: {
    question_id: number
    language: ProgrammingLanguage
    code: string
  }) => {
    try {
      loading.value = true
      const response = await questionApi.submitCode(data)
      
      if (response.data?.submission_id) {
        return { 
          success: true,
          submission_id: response.data.submission_id, 
          status: response.data.status, 
          execution_time: response.data.execution_time,
          memory_used: response.data.memory_used,
          error_message: response.data.error_message,
          beat_number: response.data.beat_number,
          message: '提交成功'
        }
      }
      
      return { success: false, message: '提交失败' }
    } catch (error) {
      console.error('Submit code error:', error)
      return { success: false, message: '提交失败，请稍后重试' }
    } finally {
      loading.value = false
    }
  }

  // 获取提交详情
  const fetchSubmission = async (submissionId: number) => {
    try {
      const response = await questionApi.getSubmission(submissionId)
      return response.data || null
    } catch (error) {
      console.error('Fetch submission error:', error)
      return null
    }
  }

  // 获取题目的提交记录
  const fetchQuestionSubmissions = async (questionId: number, params = {}) => {
    try {
      loading.value = true
      const response = await questionApi.getQuestionSubmissions(questionId, params)
      
      if (response.data) {
        submissions.value = response.data.data
        return response.data
      }
      
      return null
    } catch (error) {
      console.error('Fetch question submissions error:', error)
      return null
    } finally {
      loading.value = false
    }
  }

  // 获取推荐题目
  const fetchRecommendedQuestions = async (params = {}) => {
    try {
      const response = await questionApi.getRecommendedQuestions(params)
      return response.data || []
    } catch (error) {
      console.error('Fetch recommended questions error:', error)
      return []
    }
  }

  // 获取今日推荐题目
  const fetchDailyQuestion = async () => {
    try {
      const response = await questionApi.getDailyQuestion()
      return response.data || null
    } catch (error) {
      console.error('Fetch daily question error:', error)
      return null
    }
  }

  // 点赞题目
  const likeQuestion = async (questionId: number) => {
    try {
      await questionApi.likeQuestion(questionId)
      
      // 更新本地状态
      const question = questions.value.find(q => q.id === questionId)
      if (question) {
        question.like_count += 1
        ;(question as any).is_liked = true
      }
      
      if (currentQuestion.value?.id === questionId) {
        currentQuestion.value.like_count += 1
        ;(currentQuestion.value as any).is_liked = true
      }
      
      return true
    } catch (error) {
      console.error('Like question error:', error)
      return false
    }
  }

  // 取消点赞题目
  const unlikeQuestion = async (questionId: number) => {
    try {
      await questionApi.unlikeQuestion(questionId)
      
      // 更新本地状态
      const question = questions.value.find(q => q.id === questionId)
      if (question) {
        question.like_count = Math.max(0, question.like_count - 1)
        ;(question as any).is_liked = false
      }
      
      if (currentQuestion.value?.id === questionId) {
        currentQuestion.value.like_count = Math.max(0, currentQuestion.value.like_count - 1)
        ;(currentQuestion.value as any).is_liked = false
      }
      
      return true
    } catch (error) {
      console.error('Unlike question error:', error)
      return false
    }
  }

  // 重置状态
  const reset = () => {
    questions.value = []
    currentQuestion.value = null
    favorites.value = []
    submissions.value = []
    clearFilters()
  }

  return {
    // 状态
    questions,
    currentQuestion,
    tags,
    favorites,
    submissions,
    loading,
    pagination,
    filters,
    
    // 计算属性
    hasQuestions,
    hasTags,
    isFiltered,
    
    // 方法
    fetchQuestions,
    fetchQuestion,
    fetchTags,
    setFilters,
    clearFilters,
    searchQuestions,
    fetchFavoriteQuestions,
    favoriteQuestion,
    unfavoriteQuestion,
    submitCode,
    fetchSubmission,
    fetchQuestionSubmissions,
    fetchRecommendedQuestions,
    fetchDailyQuestion,
    likeQuestion,
    unlikeQuestion,
    reset
  }
})

